home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 9 / Example 9.2 / terrain.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-07-15  |  26.4 KB  |  976 lines

  1. #include "terrain.h"
  2. #include "camera.h"
  3.  
  4. const DWORD TERRAINVertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX2;
  5.  
  6. //////////////////////////////////////////////////////////////////////////////////////////
  7. //                                    PATCH                                                //
  8. //////////////////////////////////////////////////////////////////////////////////////////
  9.  
  10. PATCH::PATCH()
  11. {
  12.     m_pDevice = NULL;
  13.     m_pMesh = NULL;
  14. }
  15. PATCH::~PATCH()
  16. {
  17.     Release();
  18. }
  19.  
  20. void PATCH::Release()
  21. {
  22.     if(m_pMesh != NULL)
  23.         m_pMesh->Release();
  24.     m_pMesh = NULL;
  25. }
  26.  
  27. HRESULT PATCH::CreateMesh(TERRAIN &ter, RECT source, IDirect3DDevice9* Dev)
  28. {
  29.     if(m_pMesh != NULL)
  30.     {
  31.         m_pMesh->Release();
  32.         m_pMesh = NULL;
  33.     }
  34.  
  35.     try
  36.     {
  37.         m_pDevice = Dev;
  38.         m_mapRect = source;
  39.  
  40.         int width = source.right - source.left;
  41.         int height = source.bottom - source.top;
  42.         int nrVert = (width + 1) * (height + 1);
  43.         int nrTri = width * height * 2;
  44.  
  45.         if(FAILED(D3DXCreateMeshFVF(nrTri, nrVert, D3DXMESH_MANAGED, TERRAINVertex::FVF, m_pDevice, &m_pMesh)))
  46.         {
  47.             debug.Print("Couldn't create m_pMesh for PATCH");
  48.             return E_FAIL;
  49.         }
  50.  
  51.         m_BBox.max = D3DXVECTOR3(-10000.0f, -10000.0f, -10000.0f);
  52.         m_BBox.min = D3DXVECTOR3(10000.0f, 10000.0f, 10000.0f);
  53.  
  54.         //Create vertices
  55.         TERRAINVertex* ver = 0;
  56.         m_pMesh->LockVertexBuffer(0,(void**)&ver);
  57.         for(int z=source.top, z0 = 0;z<=source.bottom;z++, z0++)
  58.             for(int x=source.left, x0 = 0;x<=source.right;x++, x0++)
  59.             {
  60.                 MAPTILE *tile = ter.GetTile(x, z);
  61.  
  62.                 D3DXVECTOR3 pos = D3DXVECTOR3(x, tile->m_height, -z);
  63.                 D3DXVECTOR2 alphaUV = D3DXVECTOR2(x / (float)ter.m_size.x, z / (float)ter.m_size.y);        //Alpha UV
  64.                 D3DXVECTOR2 colorUV = alphaUV * 8.0f;                                                    //Color UV
  65.  
  66.                 ver[z0 * (width + 1) + x0] = TERRAINVertex(pos, ter.GetNormal(x, z), alphaUV, colorUV);
  67.  
  68.                 //Calculate bounding box bounds...
  69.                 if(pos.x < m_BBox.min.x)m_BBox.min.x = pos.x;
  70.                 if(pos.x > m_BBox.max.x)m_BBox.max.x = pos.x;
  71.                 if(pos.y < m_BBox.min.y)m_BBox.min.y = pos.y;
  72.                 if(pos.y > m_BBox.max.y)m_BBox.max.y = pos.y;
  73.                 if(pos.z < m_BBox.min.z)m_BBox.min.z = pos.z;
  74.                 if(pos.z > m_BBox.max.z)m_BBox.max.z = pos.z;
  75.             }
  76.         m_pMesh->UnlockVertexBuffer();
  77.  
  78.         //Calculate Indices
  79.         WORD* ind = 0;
  80.         m_pMesh->LockIndexBuffer(0,(void**)&ind);    
  81.         int index = 0;
  82.  
  83.         for(int z=source.top, z0 = 0;z<source.bottom;z++, z0++)
  84.             for(int x=source.left, x0 = 0;x<source.right;x++, x0++)
  85.             {
  86.                 //Triangle 1
  87.                 ind[index++] =   z0   * (width + 1) + x0;
  88.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  89.                 ind[index++] = (z0+1) * (width + 1) + x0;        
  90.  
  91.                 //Triangle 2
  92.                 ind[index++] = (z0+1) * (width + 1) + x0;
  93.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  94.                 ind[index++] = (z0+1) * (width + 1) + x0 + 1;
  95.             }
  96.  
  97.         m_pMesh->UnlockIndexBuffer();
  98.  
  99.         //Set Attributes
  100.         DWORD *att = 0, a = 0;
  101.         m_pMesh->LockAttributeBuffer(0,&att);
  102.         memset(att, 0, sizeof(DWORD)*nrTri);
  103.         m_pMesh->UnlockAttributeBuffer();
  104.     }
  105.     catch(...)
  106.     {
  107.         debug.Print("Error in PATCH::CreateMesh()");
  108.         return E_FAIL;
  109.     }
  110.  
  111.     return S_OK;
  112. }
  113.  
  114. void PATCH::Render()
  115. {
  116.     //Draw m_pMesh
  117.     if(m_pMesh != NULL)
  118.         m_pMesh->DrawSubset(0);
  119. }
  120.  
  121. //////////////////////////////////////////////////////////////////////////////////////////
  122. //                                    TERRAIN                                                //
  123. //////////////////////////////////////////////////////////////////////////////////////////
  124.  
  125. TERRAIN::TERRAIN()
  126. {
  127.     m_pDevice = NULL;
  128.     m_pMapTiles = NULL;
  129. }
  130.  
  131. void TERRAIN::Init(IDirect3DDevice9* Dev, INTPOINT _size)
  132. {
  133.     m_pDevice = Dev;
  134.     m_size = _size;
  135.     m_pHeightMap = NULL;
  136.  
  137.     if(m_pMapTiles != NULL)    //Clear old m_pMapTiles
  138.         delete [] m_pMapTiles;
  139.  
  140.     //Create maptiles
  141.     m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  142.     memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  143.  
  144.     //Clear old textures
  145.     for(int i=0;i<m_diffuseMaps.size();i++)
  146.         m_diffuseMaps[i]->Release();
  147.     m_diffuseMaps.clear();
  148.  
  149.     //Load textures
  150.     IDirect3DTexture9* grass = NULL, *mount = NULL, *snow = NULL;
  151.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/grass.jpg", &grass)))debug.Print("Could not load grass.jpg");
  152.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/mountain.jpg", &mount)))debug.Print("Could not load mountain.jpg");
  153.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/snow.jpg", &snow)))debug.Print("Could not load snow.jpg");
  154.     m_diffuseMaps.push_back(grass);
  155.     m_diffuseMaps.push_back(mount);
  156.     m_diffuseMaps.push_back(snow);
  157.     m_pAlphaMap = NULL;
  158.     m_pLightMap = NULL;
  159.  
  160.     // Init font
  161.     D3DXCreateFont(m_pDevice, 40, 0, 0, 1, false,  
  162.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  163.                    DEFAULT_PITCH | FF_DONTCARE, "Arial Black", &m_pProgressFont);
  164.  
  165.     //Load pixel & vertex shaders
  166.     m_dirToSun = D3DXVECTOR3(1.0f, 0.6f, 0.5f);
  167.     D3DXVec3Normalize(&m_dirToSun, &m_dirToSun);
  168.  
  169.     m_terrainPS.Init(Dev, "shaders/terrain.ps", PIXEL_SHADER);
  170.     m_terrainVS.Init(Dev, "shaders/terrain.vs", VERTEX_SHADER);
  171.     m_vsMatW = m_terrainVS.GetConstant("matW");
  172.     m_vsMatVP = m_terrainVS.GetConstant("matVP");
  173.     m_vsDirToSun = m_terrainVS.GetConstant("DirToSun");
  174.  
  175.     m_objectsPS.Init(Dev, "shaders/objects.ps", PIXEL_SHADER);
  176.     m_objectsVS.Init(Dev, "shaders/objects.vs", VERTEX_SHADER);
  177.     m_objMatW = m_objectsVS.GetConstant("matW");
  178.     m_objMatVP = m_objectsVS.GetConstant("matVP");
  179.     m_objDirToSun = m_objectsVS.GetConstant("DirToSun");
  180.     m_objMapSize = m_objectsVS.GetConstant("mapSize");
  181.  
  182.     //Create white material    
  183.     m_mtrl.Ambient = m_mtrl.Specular = m_mtrl.Diffuse  = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
  184.     m_mtrl.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
  185.  
  186.     GenerateRandomTerrain(9);
  187. }
  188.  
  189. void TERRAIN::Release()
  190. {
  191.     for(int i=0;i<m_patches.size();i++)
  192.         if(m_patches[i] != NULL)
  193.             m_patches[i]->Release();
  194.  
  195.     m_patches.clear();
  196.  
  197.     if(m_pHeightMap != NULL)
  198.     {
  199.         m_pHeightMap->Release();
  200.         delete m_pHeightMap;
  201.         m_pHeightMap = NULL;
  202.     }
  203.  
  204.     m_objects.clear();
  205. }
  206.  
  207. void TERRAIN::GenerateRandomTerrain(int numPatches)
  208. {
  209.     try
  210.     {
  211.         Release();
  212.  
  213.         //Create two heightmaps and multiply them
  214.         m_pHeightMap = new HEIGHTMAP(m_size, 20.0f);
  215.         HEIGHTMAP hm2(m_size, 2.0f);
  216.  
  217.         m_pHeightMap->CreateRandomHeightMap(rand()%2000, 1.0f, 0.7f, 7);
  218.         hm2.CreateRandomHeightMap(rand()%2000, 2.5f, 0.8f, 3);
  219.  
  220.         hm2.Cap(hm2.m_maxHeight * 0.4f);
  221.  
  222.         *m_pHeightMap *= hm2;
  223.         hm2.Release();
  224.         
  225.         //Add objects
  226.         HEIGHTMAP hm3(m_size, 1.0f);
  227.         hm3.CreateRandomHeightMap(rand()%1000, 5.5f, 0.9f, 7);
  228.  
  229.         for(int y=0;y<m_size.y;y++)
  230.             for(int x=0;x<m_size.x;x++)
  231.             {
  232.                 if(m_pHeightMap->GetHeight(x, y) == 0.0f && hm3.GetHeight(x, y) > 0.7f && rand()%6 == 0)
  233.                     AddObject(0, INTPOINT(x, y));    //Tree
  234.                 else if(m_pHeightMap->GetHeight(x, y) >= 1.0f && hm3.GetHeight(x, y) > 0.9f && rand()%20 == 0)
  235.                     AddObject(1, INTPOINT(x, y));    //Stone
  236.             }
  237.  
  238.         hm3.Release();
  239.  
  240.         InitPathfinding();
  241.         CreatePatches(numPatches);
  242.         CalculateAlphaMaps();
  243.         CalculateLightMap(false);
  244.     }
  245.     catch(...)
  246.     {
  247.         debug.Print("Error in TERRAIN::GenerateRandomTerrain()");
  248.     }
  249. }
  250.  
  251. void TERRAIN::CreatePatches(int numPatches)
  252. {
  253.     try
  254.     {
  255.         //Clear any old m_patches
  256.         for(int i=0;i<m_patches.size();i++)
  257.             if(m_patches[i] != NULL)
  258.                 m_patches[i]->Release();
  259.         m_patches.clear();
  260.  
  261.         //Create new patches
  262.         for(int y=0;y<numPatches;y++)
  263.         {
  264.             Progress("Creating Terrain Mesh", y / (float)numPatches);
  265.  
  266.             for(int x=0;x<numPatches;x++)
  267.             {
  268.                 RECT r = {x * (m_size.x - 1) / (float)numPatches, 
  269.                         y * (m_size.y - 1) / (float)numPatches, 
  270.                         (x+1) * (m_size.x - 1) / (float)numPatches,
  271.                         (y+1) * (m_size.y - 1) / (float)numPatches};
  272.                         
  273.                 PATCH *p = new PATCH();
  274.                 p->CreateMesh(*this, r, m_pDevice);
  275.                 m_patches.push_back(p);
  276.             }
  277.         }
  278.     }
  279.     catch(...)
  280.     {
  281.         debug.Print("Error in TERRAIN::CreatePatches()");
  282.     }
  283. }
  284.  
  285. void TERRAIN::CalculateAlphaMaps()
  286. {
  287.     Progress("Creating Alpha Map", 0.0f);
  288.  
  289.     //Clear old alpha maps
  290.     if(m_pAlphaMap != NULL)
  291.         m_pAlphaMap->Release();
  292.  
  293.     //Create new alpha map
  294.     D3DXCreateTexture(m_pDevice, 128, 128, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pAlphaMap);
  295.  
  296.     //Lock the texture
  297.     D3DLOCKED_RECT sRect;
  298.     m_pAlphaMap->LockRect(0, &sRect, NULL, NULL);
  299.     BYTE *bytes = (BYTE*)sRect.pBits;
  300.     memset(bytes, 0, 128*sRect.Pitch);        //Clear texture to black
  301.  
  302.     for(int i=0;i<m_diffuseMaps.size();i++)
  303.         for(int y=0;y<sRect.Pitch / 4;y++)
  304.             for(int x=0;x<sRect.Pitch / 4;x++)
  305.             {
  306.                 int terrain_x = m_size.x * (x / (float)(sRect.Pitch / 4.0f));
  307.                 int terrain_y = m_size.y * (y / (float)(sRect.Pitch / 4.0f));
  308.                 MAPTILE *tile = GetTile(terrain_x, terrain_y);
  309.  
  310.                 if(tile != NULL && tile->m_type == i)
  311.                     bytes[y * sRect.Pitch + x * 4 + i] = 255;
  312.             }
  313.  
  314.     //Unlock the texture
  315.     m_pAlphaMap->UnlockRect(0);
  316.     
  317.     //D3DXSaveTextureToFile("alpha.bmp", D3DXIFF_BMP, m_pAlphaMap, NULL);
  318. }
  319.  
  320. void TERRAIN::CalculateLightMap(bool allWhite)
  321. {
  322.     try
  323.     {
  324.         //Clear old alpha maps
  325.         if(m_pLightMap != NULL)
  326.             m_pLightMap->Release();
  327.  
  328.         //Create new light map
  329.         D3DXCreateTexture(m_pDevice, 256, 256, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8, D3DPOOL_DEFAULT, &m_pLightMap);
  330.  
  331.         //Lock the texture
  332.         D3DLOCKED_RECT sRect;
  333.         m_pLightMap->LockRect(0, &sRect, NULL, NULL);
  334.         BYTE *bytes = (BYTE*)sRect.pBits;
  335.         memset(bytes, 255, 256*sRect.Pitch);        //Clear texture to white
  336.  
  337.         if(allWhite)
  338.         {
  339.             m_pLightMap->UnlockRect(0);
  340.             return;
  341.         }
  342.  
  343.         for(int y=0;y<sRect.Pitch;y++)
  344.         {
  345.             Progress("Calculating Lightmap", y / (float)sRect.Pitch);
  346.  
  347.             for(int x=0;x<sRect.Pitch;x++)
  348.             {
  349.                 float terrain_x = (float)m_size.x * (x / (float)(sRect.Pitch));
  350.                 float terrain_z = (float)m_size.y * (y / (float)(sRect.Pitch));
  351.  
  352.                 //Find patch that the terrain_x, terrain_z is over
  353.                 bool done = false;
  354.                 for(int p=0;p<m_patches.size() && !done;p++)
  355.                 {
  356.                     RECT mr = m_patches[p]->m_mapRect;
  357.  
  358.                     //Focus within patch maprect or not?
  359.                     if(terrain_x >= mr.left && terrain_x < mr.right &&
  360.                          terrain_z >= mr.top && terrain_z < mr.bottom)
  361.                     {            
  362.                         // Collect only the closest intersection
  363.                         RAY rayTop(D3DXVECTOR3(terrain_x, 10000.0f, -terrain_z), D3DXVECTOR3(0.0f, -1.0f, 0.0f));
  364.                         float dist = rayTop.Intersect(m_patches[p]->m_pMesh);
  365.  
  366.                         if(dist >= 0.0f)
  367.                         {
  368.                             RAY ray(D3DXVECTOR3(terrain_x, 10000.0f - dist + 0.01f, -terrain_z), m_dirToSun);
  369.  
  370.                             for(int p2=0;p2<m_patches.size() && !done;p2++)
  371.                                 if(ray.Intersect(m_patches[p2]->m_BBox) >= 0)
  372.                                 {
  373.                                     if(ray.Intersect(m_patches[p2]->m_pMesh) >= 0)    //In shadow
  374.                                     {
  375.                                         done = true;
  376.                                         bytes[y * sRect.Pitch + x] = 128;
  377.                                     }
  378.                                 }
  379.  
  380.                             done = true;
  381.                         }
  382.                     }
  383.                 }                        
  384.             }
  385.         }
  386.  
  387.         //Smooth lightmap        
  388.         for(int i=0;i<3;i++)
  389.         {
  390.             Progress("Smoothing the Lightmap", i / 3.0f);
  391.  
  392.             BYTE* tmpBytes = new BYTE[sRect.Pitch * sRect.Pitch];
  393.             memcpy(tmpBytes, sRect.pBits, sRect.Pitch * sRect.Pitch);
  394.  
  395.             for(int y=1;y<sRect.Pitch-1;y++)
  396.                 for(int x=1;x<sRect.Pitch-1;x++)
  397.                 {
  398.                     long index = y*sRect.Pitch + x;
  399.                     BYTE b1 = bytes[index];
  400.                     BYTE b2 = bytes[index - 1];
  401.                     BYTE b3 = bytes[index - sRect.Pitch];
  402.                     BYTE b4 = bytes[index + 1];
  403.                     BYTE b5 = bytes[index + sRect.Pitch];
  404.                     
  405.                     tmpBytes[index] = (BYTE)((b1 + b2 + b3 + b4 + b5) / 5);
  406.                 }
  407.  
  408.             memcpy(sRect.pBits, tmpBytes, sRect.Pitch * sRect.Pitch);
  409.             delete [] tmpBytes;
  410.         }
  411.  
  412.         //Unlock the texture
  413.         m_pLightMap->UnlockRect(0);
  414.         
  415.         //D3DXSaveTextureToFile("light.bmp", D3DXIFF_BMP, m_pLightMap, NULL);
  416.     }
  417.     catch(...)
  418.     {
  419.         debug.Print("Error in TERRAIN::CalculateLightMap()");
  420.     }
  421. }
  422.  
  423. D3DXVECTOR3 TERRAIN::GetNormal(int x, int y)
  424. {
  425.     //Neighboring map nodes (D, B, C, F, H, G)
  426.     INTPOINT mp[] = {INTPOINT(x-1, y),   INTPOINT(x, y-1), 
  427.                      INTPOINT(x+1, y-1), INTPOINT(x+1, y),
  428.                        INTPOINT(x, y+1),   INTPOINT(x-1, y+1)};
  429.  
  430.     //if there's an invalid map node return (0, 1, 0)
  431.     if(!Within(mp[0]) || !Within(mp[1]) || !Within(mp[2]) || 
  432.        !Within(mp[3]) || !Within(mp[4]) || !Within(mp[5]))
  433.         return D3DXVECTOR3(0.0f, 1.0f, 0.0f);
  434.  
  435.     //Calculate the normals of the 6 neighboring planes
  436.     D3DXVECTOR3 normal = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
  437.  
  438.     for(int i=0;i<6;i++)
  439.     {
  440.         D3DXPLANE plane;
  441.         D3DXPlaneFromPoints(&plane, 
  442.                             &GetWorldPos(INTPOINT(x, y)),
  443.                             &GetWorldPos(mp[i]), 
  444.                             &GetWorldPos(mp[(i + 1) % 6]));
  445.  
  446.         normal +=  D3DXVECTOR3(plane.a, plane.b, plane.c);
  447.     }
  448.  
  449.     D3DXVec3Normalize(&normal, &normal);
  450.     return normal;
  451. }
  452.  
  453. void TERRAIN::AddObject(int type, INTPOINT mappos)
  454. {
  455.     D3DXVECTOR3 pos = D3DXVECTOR3(mappos.x, m_pHeightMap->GetHeight(mappos), -mappos.y);    
  456.     D3DXVECTOR3 rot = D3DXVECTOR3((rand()%1000 / 1000.0f) * 0.13f, (rand()%1000 / 1000.0f) * 3.0f, (rand()%1000 / 1000.0f) * 0.13);
  457.  
  458.     float sca_xz = (rand()%1000 / 1000.0f) * 0.5f + 0.5f;
  459.     float sca_y = (rand()%1000 / 1000.0f) * 1.0f + 0.5f;
  460.     D3DXVECTOR3 sca = D3DXVECTOR3(sca_xz, sca_y, sca_xz);
  461.  
  462.     m_objects.push_back(OBJECT(type, mappos, pos, rot, sca));
  463. }
  464.  
  465. void TERRAIN::Render(CAMERA &camera)
  466. {
  467.     //Set render states        
  468.     m_pDevice->SetRenderState(D3DRS_LIGHTING, false);
  469.     m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true);    
  470.     
  471.     m_pDevice->SetTexture(0, m_pAlphaMap);
  472.     m_pDevice->SetTexture(1, m_diffuseMaps[0]);        //Grass
  473.     m_pDevice->SetTexture(2, m_diffuseMaps[1]);        //Mountain
  474.     m_pDevice->SetTexture(3, m_diffuseMaps[2]);        //Snow
  475.     m_pDevice->SetTexture(4, m_pLightMap);            //Lightmap
  476.     m_pDevice->SetMaterial(&m_mtrl);
  477.  
  478.     D3DXMATRIX world, vp = camera.GetViewMatrix() * camera.GetProjectionMatrix();
  479.     D3DXMatrixIdentity(&world);
  480.     m_pDevice->SetTransform(D3DTS_WORLD, &world);
  481.     
  482.     //Set vertex shader variables
  483.     m_terrainVS.SetMatrix(m_vsMatW, world);
  484.     m_terrainVS.SetMatrix(m_vsMatVP, vp);
  485.     m_terrainVS.SetVector3(m_vsDirToSun, m_dirToSun);
  486.  
  487.     m_terrainVS.Begin();
  488.     m_terrainPS.Begin();
  489.         
  490.     for(int p=0;p<m_patches.size();p++)
  491.         if(!camera.Cull(m_patches[p]->m_BBox))
  492.             m_patches[p]->Render();
  493.  
  494.     m_terrainPS.End();
  495.     m_terrainVS.End();
  496.  
  497.     m_pDevice->SetTexture(1, NULL);
  498.     m_pDevice->SetTexture(2, NULL);
  499.     m_pDevice->SetTexture(3, NULL);
  500.     m_pDevice->SetTexture(4, NULL);
  501.  
  502.     //Render Objects
  503.     m_objectsVS.SetMatrix(m_objMatW, world);
  504.     m_objectsVS.SetMatrix(m_objMatVP, vp);
  505.     m_objectsVS.SetVector3(m_objDirToSun, m_dirToSun);
  506.     m_objectsVS.SetVector3(m_objMapSize, D3DXVECTOR3(m_size.x, m_size.y, 0.0f));
  507.  
  508.     m_pDevice->SetTexture(1, m_pLightMap);        //Lightmap
  509.     
  510.     m_objectsVS.Begin();
  511.     m_objectsPS.Begin();
  512.  
  513.     for(int i=0;i<m_objects.size();i++)
  514.         if(!camera.Cull(m_objects[i].m_BBox))
  515.         {
  516.             D3DXMATRIX m = m_objects[i].m_meshInstance.GetWorldMatrix();
  517.             m_objectsVS.SetMatrix(m_objMatW, m);
  518.             m_objects[i].Render();
  519.         }
  520.  
  521.     m_objectsVS.End();
  522.     m_objectsPS.End();
  523. }
  524.  
  525. void TERRAIN::Progress(std::string text, float prc)
  526. {
  527.     m_pDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  528.     m_pDevice->BeginScene();
  529.     
  530.     RECT rc = {200, 250, 600, 300};
  531.     m_pProgressFont->DrawText(NULL, text.c_str(), -1, &rc, DT_CENTER | DT_VCENTER | DT_NOCLIP, 0xff000000);
  532.     
  533.     //Progress bar
  534.     D3DRECT r;
  535.     r.x1 = 200; r.x2 = 600;
  536.     r.y1 = 300; r.y2 = 340;
  537.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.0f, 0L);
  538.     r.x1 = 202; r.x2 = 598;
  539.     r.y1 = 302; r.y2 = 338;
  540.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  541.     r.x1 = 202; r.x2 = 202 + 396 * prc;
  542.     r.y1 = 302; r.y2 = 338;
  543.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff00ff00, 1.0f, 0L);
  544.  
  545.     m_pDevice->EndScene();
  546.     m_pDevice->Present(0, 0, 0, 0);
  547. }
  548.  
  549. bool TERRAIN::Within(INTPOINT p)
  550. {
  551.     return p.x >= 0 && p.y >= 0 && p.x < m_size.x && p.y < m_size.y;
  552. }
  553.  
  554. void TERRAIN::InitPathfinding()
  555. {
  556.     try
  557.     {
  558.         //Read maptile heights & types from heightmap
  559.         for(int y=0;y<m_size.y;y++)
  560.             for(int x=0;x<m_size.x;x++)
  561.             {
  562.                 MAPTILE *tile = GetTile(x, y);
  563.                 if(m_pHeightMap != NULL)tile->m_height = m_pHeightMap->GetHeight(x, y);
  564.                 tile->m_mappos = INTPOINT(x, y);
  565.                 
  566.                 if(tile->m_height < 0.3f)         tile->m_type = 0;    //Grass
  567.                 else if(tile->m_height < 7.0f) tile->m_type = 1;    //Stone
  568.                 else                         tile->m_type = 2;    //Snow
  569.             }
  570.  
  571.         //Calculate tile cost as a function of the height variance
  572.         for(int y=0;y<m_size.y;y++)        
  573.             for(int x=0;x<m_size.x;x++)
  574.             {
  575.                 MAPTILE *tile = GetTile(x, y);
  576.  
  577.                 if(tile != NULL)
  578.                 {
  579.                     //Possible m_pNeighbors
  580.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  581.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  582.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  583.  
  584.                     float variance = 0.0f;
  585.                     int nr = 0;
  586.  
  587.                     //For each neighbor
  588.                     for(int i=0;i<8;i++)    
  589.                         if(Within(p[i]))
  590.                         {
  591.                             MAPTILE *neighbor = GetTile(p[i]);
  592.  
  593.                             if(neighbor != NULL)
  594.                             {
  595.                                 float v = neighbor->m_height - tile->m_height;
  596.                                 variance += (v * v);
  597.                                 nr++;
  598.                             }
  599.                         }
  600.  
  601.                     //Cost = height variance
  602.                     variance /= (float)nr;
  603.                     tile->m_cost = variance + 0.1f;
  604.                     if(tile->m_cost > 1.0f)tile->m_cost = 1.0f;
  605.  
  606.                     //If the tile cost is less than 1.0f, then we can walk on the tile
  607.                     tile->m_walkable = tile->m_cost < 0.5f;
  608.                 }
  609.             }
  610.  
  611.         //Make maptiles with objects on them not walkable
  612.         for(int i=0;i<m_objects.size();i++)
  613.         {
  614.             MAPTILE *tile = GetTile(m_objects[i].m_mappos);
  615.             if(tile != NULL)
  616.             {
  617.                 tile->m_walkable = false;
  618.                 tile->m_cost = 1.0f;
  619.             }
  620.         }
  621.  
  622.         //Connect maptiles using the neightbors[] pointers
  623.         for(int y=0;y<m_size.y;y++)        
  624.             for(int x=0;x<m_size.x;x++)
  625.             {
  626.                 MAPTILE *tile = GetTile(x, y);
  627.                 if(tile != NULL && tile->m_walkable)
  628.                 {
  629.                     //Clear old connections
  630.                     for(int i=0;i<8;i++)
  631.                         tile->m_pNeighbors[i] = NULL;
  632.  
  633.                     //Possible m_pNeighbors
  634.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  635.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  636.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  637.  
  638.                     //For each neighbor
  639.                     for(int i=0;i<8;i++)    
  640.                         if(Within(p[i]))
  641.                         {
  642.                             MAPTILE *neighbor = GetTile(p[i]);
  643.  
  644.                             //Connect tiles if the neighbor is walkable
  645.                             if(neighbor != NULL && neighbor->m_walkable)
  646.                                 tile->m_pNeighbors[i] = neighbor;
  647.                         }
  648.                 }
  649.             }
  650.  
  651.         CreateTileSets();
  652.     }
  653.     catch(...)
  654.     {
  655.         debug.Print("Error in InitPathfinding()");
  656.     }    
  657. }
  658.  
  659. void TERRAIN::UpdatePathfinding(RECT *r)
  660. {
  661.     if(r == NULL)
  662.     {
  663.         InitPathfinding();
  664.         return;
  665.     }
  666.  
  667.     //Connect maptiles using the neightbors[] pointers
  668.     for(int y=r->top; y<=r->bottom; y++)        
  669.         for(int x=r->left; x<=r->right; x++)
  670.         {
  671.             MAPTILE *tile = GetTile(x, y);
  672.             if(tile != NULL && tile->m_walkable)
  673.             {
  674.                 //Clear old connections
  675.                 for(int i=0;i<8;i++)
  676.                     tile->m_pNeighbors[i] = NULL;
  677.  
  678.                 //Possible m_pNeighbors
  679.                 INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  680.                                 INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  681.                                 INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  682.  
  683.                 //For each neighbor
  684.                 for(int i=0;i<8;i++)
  685.                     if(Within(p[i]))
  686.                     {
  687.                         MAPTILE *neighbor = GetTile(p[i]);
  688.  
  689.                         //Connect tiles if the neighbor is walkable
  690.                         if(neighbor != NULL && neighbor->m_walkable)
  691.                             tile->m_pNeighbors[i] = neighbor;
  692.                     }
  693.             }
  694.         }
  695.  
  696.     CreateTileSets();
  697. }
  698.  
  699. void TERRAIN::CreateTileSets()
  700. {
  701.     try
  702.     {
  703.         int setNo = 0;
  704.         for(int y=0;y<m_size.y;y++)        //Set a unique set for each tile...
  705.             for(int x=0;x<m_size.x;x++)
  706.                 m_pMapTiles[x + y * m_size.x].m_set = setNo++;
  707.  
  708.         bool changed = true;
  709.         while(changed)
  710.         {
  711.             changed = false;
  712.  
  713.             for(int y=0;y<m_size.y;y++)
  714.                 for(int x=0;x<m_size.x;x++)
  715.                 {
  716.                     MAPTILE *tile = GetTile(x, y);
  717.  
  718.                     //Find the lowest set of a neighbor
  719.                     if(tile != NULL && tile->m_walkable)
  720.                     {
  721.                         for(int i=0;i<8;i++)
  722.                             if(tile->m_pNeighbors[i] != NULL &&
  723.                                 tile->m_pNeighbors[i]->m_walkable &&
  724.                                 tile->m_pNeighbors[i]->m_set < tile->m_set)
  725.                             {
  726.                                 changed = true;
  727.                                 tile->m_set = tile->m_pNeighbors[i]->m_set;
  728.                             }
  729.                     }
  730.                 }
  731.         }
  732.     }
  733.     catch(...)
  734.     {
  735.         debug.Print("Error in TERRAIN::CreateTileSets()");
  736.     }
  737. }
  738.  
  739. float H(INTPOINT a, INTPOINT b)
  740. {
  741.     //return abs(a.x - b.x) + abs(a.y - b.y);
  742.     return a.Distance(b);
  743. }
  744.  
  745. std::vector<INTPOINT> TERRAIN::GetPath(INTPOINT start, INTPOINT goal)
  746. {
  747.     try
  748.     {
  749.         //Check that the two points are within the bounds of the map
  750.         MAPTILE *startTile = GetTile(start);
  751.         MAPTILE *goalTile = GetTile(goal);
  752.  
  753.         if(!Within(start) || !Within(goal) || start == goal || startTile == NULL || goalTile == NULL)
  754.             return std::vector<INTPOINT>();
  755.  
  756.         //Check if a path exists
  757.         if(!startTile->m_walkable || !goalTile->m_walkable || startTile->m_set != goalTile->m_set)
  758.             return std::vector<INTPOINT>();
  759.  
  760.         //Init Search
  761.         long numTiles = m_size.x * m_size.y;
  762.         for(long l=0;l<numTiles;l++)
  763.         {
  764.             m_pMapTiles[l].f = m_pMapTiles[l].g = INT_MAX;        //Clear F,G
  765.             m_pMapTiles[l].open = m_pMapTiles[l].closed = false;    //Reset Open and Closed
  766.         }
  767.  
  768.         std::vector<MAPTILE*> open;                //Create Our Open list
  769.         startTile->g = 0;                        //Init our starting point (SP)
  770.         startTile->f = H(start, goal);
  771.         startTile->open = true;
  772.         open.push_back(startTile);                //Add SP to the Open list
  773.  
  774.         bool found = false;                    // Search as long as a path hasnt been found,
  775.         while(!found && !open.empty())        // or there is no more tiles to search
  776.         {                                                
  777.             MAPTILE * best = open[0];        // Find the best tile (i.e. the lowest F value)
  778.             int bestPlace = 0;
  779.             for(int i=1;i<open.size();i++)
  780.                 if(open[i]->f < best->f)
  781.                 {
  782.                     best = open[i];
  783.                     bestPlace = i;
  784.                 }
  785.             
  786.             if(best == NULL)break;            //No path found
  787.  
  788.             open[bestPlace]->open = false;
  789.             open.erase(&open[bestPlace]);    // Take the best node out of the Open list
  790.  
  791.             if(best->m_mappos == goal)        //If the goal has been found
  792.             {
  793.                 std::vector<INTPOINT> p, p2;
  794.                 MAPTILE *point = best;
  795.  
  796.                 while(point->m_mappos != start)    // Generate path
  797.                 {
  798.                     p.push_back(point->m_mappos);
  799.                     point = point->m_pParent;
  800.  
  801.                     if(p.size() > 500)        //Too long path, something is wrong
  802.                         return std::vector<INTPOINT>();
  803.                 }
  804.  
  805.                 for(int i=p.size()-1;i!=0;i--)    // Reverse path
  806.                     p2.push_back(p[i]);
  807.                 p2.push_back(goal);
  808.                 return p2;
  809.             }
  810.             else
  811.             {
  812.                 for(i=0;i<8;i++)                    // otherwise, check the neighbors of the
  813.                     if(best->m_pNeighbors[i] != NULL)    // best tile
  814.                     {
  815.                         bool inList = false;        // Generate new G and F value
  816.                         float newG = best->g + 1.0f;
  817.                         float d = H(best->m_mappos, best->m_pNeighbors[i]->m_mappos);
  818.                         float newF = newG + H(best->m_pNeighbors[i]->m_mappos, goal) + best->m_pNeighbors[i]->m_cost * 5.0f * d;
  819.  
  820.                         if(best->m_pNeighbors[i]->open || best->m_pNeighbors[i]->closed)
  821.                         {
  822.                             if(newF < best->m_pNeighbors[i]->f)    // If the new F value is lower
  823.                             {
  824.                                 best->m_pNeighbors[i]->g = newG;    // update the values of this tile
  825.                                 best->m_pNeighbors[i]->f = newF;
  826.                                 best->m_pNeighbors[i]->m_pParent = best;                                
  827.                             }
  828.                             inList = true;
  829.                         }
  830.  
  831.                         if(!inList)            // If the neighbor tile isn't in the Open or Closed list
  832.                         {
  833.                             best->m_pNeighbors[i]->f = newF;        //Set the values
  834.                             best->m_pNeighbors[i]->g = newG;
  835.                             best->m_pNeighbors[i]->m_pParent = best;
  836.                             best->m_pNeighbors[i]->open = true;
  837.                             open.push_back(best->m_pNeighbors[i]);    //Add it to the open list    
  838.                         }
  839.                     }
  840.  
  841.                 best->closed = true;        //The best tile has now been searched, add it to the Closed list
  842.             }
  843.         }
  844.  
  845.         return std::vector<INTPOINT>();        //No path found, return an empty path
  846.         
  847.     }
  848.     catch(...)
  849.     {
  850.         debug.Print("Error in TERRAIN::GetPath()");
  851.         return std::vector<INTPOINT>();
  852.     }
  853. }
  854.  
  855. MAPTILE* TERRAIN::GetTile(int x, int y)
  856. {
  857.     if(m_pMapTiles == NULL)return NULL;
  858.  
  859.     try
  860.     {
  861.         return &m_pMapTiles[x + y * m_size.x];
  862.     }
  863.     catch(...)
  864.     {
  865.         return NULL;
  866.     }
  867. }
  868.  
  869. void TERRAIN::SaveTerrain(char fileName[])
  870. {
  871.     try
  872.     {
  873.         std::ofstream out(fileName, std::ios::binary);        //Binary format
  874.  
  875.         if(out.good())
  876.         {
  877.             out.write((char*)&m_size, sizeof(INTPOINT));    //Write map size
  878.  
  879.             //Write all the maptile information needed to recreate the map
  880.             for(int y=0;y<m_size.y;y++)
  881.                 for(int x=0;x<m_size.x;x++)
  882.                 {
  883.                     MAPTILE *tile = GetTile(x, y);
  884.                     out.write((char*)&tile->m_type, sizeof(int));            //type
  885.                     out.write((char*)&tile->m_height, sizeof(float));        //Height
  886.                 }
  887.  
  888.             //Write all the objects
  889.             int numObjects = m_objects.size();
  890.             out.write((char*)&numObjects, sizeof(int));     //Num Objects
  891.             for(int i=0;i<m_objects.size();i++)
  892.             {
  893.                 out.write((char*)&m_objects[i].m_type, sizeof(int));                //type
  894.                 out.write((char*)&m_objects[i].m_mappos, sizeof(INTPOINT));            //mappos
  895.                 out.write((char*)&m_objects[i].m_meshInstance.m_pos, sizeof(D3DXVECTOR3));    //Pos
  896.                 out.write((char*)&m_objects[i].m_meshInstance.m_rot, sizeof(D3DXVECTOR3));    //Rot
  897.                 out.write((char*)&m_objects[i].m_meshInstance.m_sca, sizeof(D3DXVECTOR3));    //Sca
  898.             }
  899.         }
  900.  
  901.         out.close();
  902.     }
  903.     catch(...)
  904.     {
  905.         debug.Print("Error in TERRAIN::SaveTerrain()");
  906.     }
  907. }
  908.  
  909. void TERRAIN::LoadTerrain(char fileName[])
  910. {
  911.     try
  912.     {
  913.         std::ifstream in(fileName, std::ios::binary);        //Binary format
  914.  
  915.         if(in.good())
  916.         {
  917.             Release();    //Release all terrain resources
  918.  
  919.             in.read((char*)&m_size, sizeof(INTPOINT));    //read map size
  920.         
  921.             if(m_pMapTiles != NULL)    //Clear old maptiles
  922.                 delete [] m_pMapTiles;
  923.  
  924.             //Create new maptiles
  925.             m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  926.             memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  927.  
  928.  
  929.             //Read the maptile information
  930.             for(int y=0;y<m_size.y;y++)
  931.                 for(int x=0;x<m_size.x;x++)
  932.                 {
  933.                     MAPTILE *tile = GetTile(x, y);
  934.                     in.read((char*)&tile->m_type, sizeof(int));            //type
  935.                     in.read((char*)&tile->m_height, sizeof(float));        //Height
  936.                 }
  937.  
  938.             //Read number of objects
  939.             int numObjects = 0;
  940.             in.read((char*)&numObjects, sizeof(int));
  941.             for(int i=0;i<numObjects;i++)
  942.             {
  943.                 int type = 0;
  944.                 INTPOINT mp;
  945.                 D3DXVECTOR3 p, r, s;
  946.  
  947.                 in.read((char*)&type, sizeof(int));            //type
  948.                 in.read((char*)&mp, sizeof(INTPOINT));        //mappos
  949.                 in.read((char*)&p, sizeof(D3DXVECTOR3));    //Pos
  950.                 in.read((char*)&r, sizeof(D3DXVECTOR3));    //Rot
  951.                 in.read((char*)&s, sizeof(D3DXVECTOR3));    //Sca
  952.  
  953.                 m_objects.push_back(OBJECT(type, mp, p, r, s));
  954.             }
  955.  
  956.             //Recreate Terrain
  957.             InitPathfinding();
  958.             CreatePatches(3);
  959.             CalculateAlphaMaps();
  960.             CalculateLightMap(true);
  961.         }
  962.  
  963.         in.close();
  964.     }
  965.     catch(...)
  966.     {
  967.         debug.Print("Error in TERRAIN::LoadTerrain()");
  968.     }
  969. }
  970.  
  971. D3DXVECTOR3 TERRAIN::GetWorldPos(INTPOINT mappos)
  972. {
  973.     if(!Within(mappos))return D3DXVECTOR3(0, 0, 0);
  974.     MAPTILE *tile = GetTile(mappos);
  975.     return D3DXVECTOR3(mappos.x, tile->m_height, -mappos.y);
  976. }